<template>
  <el-dialog v-dialogDrag :title="title" modal class="pms-dialog" v-bind="$attrs" width="60%" v-on="$listeners">
    <div class="container">
      <div v-if="isShowAgent" class="select">
        <div class="box">
          <div class="title">下一步节点</div>
          <div class="content">
            <div
              v-for="(item, index) in nodeList"
              :key="index"
              class="node-item"
              :class="{ 'clicked': item.clicked }"
              @click="nodeClick(item)"
            >
              {{ item.nodeName }}
            </div>
          </div>
        </div>
        <div class="box">
          <div class="title">可选办理人</div>
          <div class="content">
            <el-tree
              ref="userTree"
              class="userTree-container"
              empty-text=""
              :data="toSelectdata"
              default-expand-all
              icon-class=""
              @current-change="currentChange"
              @node-click="userClick"
            >
              <template slot-scope="{ node, data }">
                <span class="custom-tree-node">
                  <span
                    v-if="!data.isLeaf"
                    style="margin-right: 6px;font-size: 14px;color: #606266;"
                    :class="[node.expanded ? 'el-icon-folder-opened' : 'el-icon-folder']"
                  />
                  <span v-else style="margin-right: 6px;font-size: 14px;color: #606266;" class="el-icon-user" />
                  <span style="font-size: 14px;color: #606266;">{{ data.label }}&nbsp;&nbsp;{{
                    data.isLeaf ? `(${data.id})` : '' }}</span>
                </span>
              </template>
            </el-tree>
          </div>
        </div>
        <div class="box">
          <div class="title">已选办理人</div>
          <div class="content">
            <div v-if="userSelectedName" class="user-select-item">
              <span class="el-icon-user" style="margin-right: 6px;" />
              <span>{{ userSelectedName }}&nbsp;&nbsp;{{ selectedUserId ? `(${selectedUserId})` : '' }}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="!finishNode && isShowAgent" class="nextTips">
        <span>如果待选人员为空，请联系IT专岗或地市4A管理员配置
          <span style="font-weight:bold;color:rgb(227, 47, 47);">
            【{{ roleName }}】
          </span>
          角色
        </span>
        <!-- <span>如果待选人员为空，请联系IT专岗或地市4A管理员配置【<span style="font-weight:bold;color:rgb(227, 47, 47);">信息化归口管理单位公司分管领导</span>】角色</span> -->
      </div>
      <div class="message">
        <el-form ref="nextPageForm" class="pms-details" :model="form" :rules="rules" label-width="100">
          <el-form-item label="办理意见" prop="opinion">
            <div style="display: flex; margin-right: 10px;">
              <el-button type="text" class="btnColor" @click="doOpenCommonOpinion">
                （自定义常用意见）
              </el-button>
              <el-select
                v-model="opinion"
                placeholder="请选择"
                class="pms-select"
                size="mini"
                style="margin-left: 10px"
                @change="handleSelectChange"
              >
                <el-option v-for="item in opinions" :key="item.id" :value="item.opinion" />
              </el-select>
            </div>
          </el-form-item>
          <el-input v-model="form.opinion" class="pms-textarea" type="textarea" placeholder="请输入办理意见" :rows="4" />
        </el-form>
      </div>
    </div>
    <div slot="footer">
      <el-button class="pms-button-primary" @click="confirm">确 定</el-button>
      <el-button class="pms-button-primary" @click="cancel">取 消</el-button>
    </div>

    <!--常用意见列表-->
    <common-opinion v-if="ifCommonOpinion" :visible.sync="ifCommonOpinion" @close="ifCommonOpinion = false" />
  </el-dialog>

</template>

<script>
import { txGetNextStep, getNextUsersByRole, getCommonOpinion } from '@/api/workFlow'
import CommonOpinion from '@/components/nextPerson/commonOpinionList'

export default {
  name: 'NextPage',
  components: { CommonOpinion },
  props: {
    title: {
      type: String,
      default: '流程提交'
    },
    // 流程实例ID
    processInstId: {
      type: [String, Number],
      default: ''
    },
    // 活动实例ID
    activityInstId: {
      type: [String, Number],
      default: ''
    },
    // 活动定义ID
    activityDefId: {
      type: [String, Number],
      default: ''
    },
    // 流程实例名称
    processDefName: {
      type: String,
      default: ''
    },
    // 办理意见是否必填
    opinionValid: {
      type: Boolean,
      default: true
    },
    orgId: {
      type: String,
      default: ''
    },
    orgIds: {
      type: String,
      default: ''
    },
    orgCode: {
      type: String,
      default: ''
    },
    userIds: {
      type: String,
      default: ''
    },
    // 流程下一步路由
    route: {
      type: String,
      default: ''
    },
    // 是否展示下一步节点或办理人
    isShowAgent: {
      type: Boolean,
      default: true
    },
    prjId: {
      type: String,
      default: ''
    },
    // 流程阶段
    prjStage: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      detailId: '',
      nTemplateId: '',
      nextNodeName: '',
      nodeList: [], // 下一步办理节点
      userSelected: {}, // 已选择的人员节点
      toSelectdata: [], // 可选办理人树型
      actDefIdSelected: '', // 已选择的节点id
      form: {
        opinion: '' // 办理意见
      },
      rules: {
        opinion: [
          { required: true, message: '请输入办理意见', trigger: 'change' }
          // { min: 10, message: '至少输入10个字', trigger: 'blur' }
        ]
      },
      finishNode: false,
      selectedUserId: '', // 已选办理人账号
      selectedNodeName: '', // 已选项目节点名称
      opinion: '',
      finish: false,
      opinions: [],
      roleName: '',
      ifCommonOpinion: false, // 常用意见页面
      nextSceneId: '' // 场景id
    }
  },
  computed: {
    userSelectedName() {
      return this.userSelected.empName
    }
  },
  watch: {
    opinionValid: {
      handler: function(newVal) {
        if (!newVal) {
          this.rules = {}
        }
      },
      immediate: true
    }
  },
  mounted() {
    if (this.isShowAgent) {
      this.doSearchNextActivity()
    }
    this.getCommonOpinions()
  },
  methods: {
    doSearchNextActivity() {
      txGetNextStep({
        prjId: this.prjId,
        processInstId: this.processInstId,
        actInsetId: this.activityInstId,
        prjStage: this.prjStage,
        route: this.route
      }).then(res => {
        if (+res.code !== 200) {
                  return Promise.reject(res)
        }
        const { data } = res
        this.nodeList = data
        if (data.length > 0) {
          // 默认选中第一个节点
          this.nodeClick(data[0])
        }
      })
    },
    // 获取节点可选办理人
    doSearchNextUsersByRole(item) {
      const param = {
        'procInstId': this.processInstId,
        'nodeId': item.nodeId,
        'userIds': this.userIds,
        'orgCode': this.orgCode,
        'orgId': this.orgId,
        'detailId': item.detailId,
        'templateId': item.templateId
      }
      this.finish = item.procEnd
      getNextUsersByRole(param).then(res => {
        if (+res.code !== 200) {
                  return Promise.reject(res)
        }
        this.toSelectdata = res.data
      })
    },
    // 选择节点
    nodeClick(item) {
      this.nodeList.forEach(i => {
        i.clicked = false
      })
      item.clicked = true
      this.finishNode = item.finishNode
      this.actDefIdSelected = item.nodeId
      this.selectedNodeName = item.nodeName
      this.roleName = item.roleName
      this.nextSceneId = item.sceneId
      this.procEnd = item.procEnd
      this.detailId = item.detailId
      this.nTemplateId = item.templateId
      this.nextNodeName = item.nodeName
      // procEnd表示当前阶段流程结束，finishNode表示当前节点是否为结束节点；例：跨阶段时，procEnd为true，finishNode为false
      if (!item.finishNode) {
        this.doSearchNextUsersByRole(item)
      } else {
        console.log('流程结束，没有可选办理人')
      }
    },
    currentChange(data, node) {
      console.log("[]");
    },
    userClick(data, node) {
      if (data.isLeaf && node.expanded) {
        const { id: empId, label: empName } = data
        this.userSelected = { empId, empName }
        this.selectedUserId = data.id
      }
    },
    // 提交后返回值
    doEmit() {
      this.$emit('selected', this.userSelected)
      this.$emit('doNextEntity', {
        processInstId: this.processInstId,
        processDefId: this.processDefId,
        actDefId: this.activityDefId,
        templateId: this.processDefName, // 模板id
        nodeId: this.actDefIdSelected, // 节点id
        route: this.route, // 路由
        opinion: this.form.opinion, // 审批意见
        finishNode: this.finishNode, // 当前已选择节点是否为结束节点
        finish: this.finish,
        procEnd: this.procEnd, // 当前阶段流程是否结束
        nextSceneId: this.nextSceneId, // 场景id
        detailId: this.detailId,
        nTemplateId: this.nTemplateId,
        nodeName: this.nextNodeName,
        ...this.userSelected
      })
      this.$emit('update:visible', false)
    },
    // 确认
    confirm() {
      if (this.isShowAgent && !this.finishNode && !Object.keys(this.userSelected).length) {
        this.$message({
          message: '请选择下一节点办理人',
          type: 'error'
        })
        return
      }
      this.opinionValid && this.$refs['nextPageForm'].validate((valid) => {
        // 校验通过
        valid && this.doEmit()
      })
      if (!this.opinionValid) {
        this.doEmit()
      }
    },
    // 取消
    cancel() {
      this.$refs['nextPageForm'].resetFields()
      this.$emit('selected', {})
      this.$emit('update:visible', false)
    },
    handleSelectChange(value) {
      this.$set(this.form, 'opinion', value)
    },
    // 获取常用意见
    getCommonOpinions() {
      getCommonOpinion().then(res => {
        if (+res.code !== 200) {
                  return Promise.reject(res)
        }
        this.opinions = res.data
      })
    },
    // 打开常用意见页面
    doOpenCommonOpinion() {
      this.ifCommonOpinion = true
    }
  }
}
</script>
<style lang='scss' scoped>
::v-deep .el-dialog__body {
  padding: 20px;
}

.container {
  .select {
    display: flex;
    align-items: center;

    .box {
      width: 100%;

      &:nth-child(n+2) {
        margin-left: 10px;
      }
    }

    .title {
      width: 100%;
      height: 36px;
      line-height: 36px;
      text-align: left;
      font-size: 17px;
      font-weight: 900;
      // color: rgb(227, 47, 47);
      color: #eb4b4b;
    }

    .content {
      height: 250px;
      border: 1px solid #ccc;
      overflow: hidden;

      .node-item {
        height: 30px;
        line-height: 30px;
        //   text-align: left;
        text-indent: 1em;
        font-size: 12px;
        width: 100%;
        background-color: #DBDBDB;

        &:hover {
          cursor: pointer;
        }

        &.clicked {
          background-color: #ffefe5;
          color: #eb4b4b;
        }
      }

      .user-item {
        height: 22px;
        line-height: 22px;
      }

      .user-select-item {
        height: 30px;
        line-height: 30px;
        text-align: center;
        font-size: 12px;
        width: 100%;
        background-color: #F4F6F8;
      }
    }

    .icon {
      margin-right: 6px;
      font-size: 14px;
    }

    ::v-deep .el-icon-caret-right:before {
      content: ''
    }
  }

  .message {
    //margin-top: 10px;
    text-align: left;
  }

  .nextTips {
    margin-top: 5px;
    text-align: left;
  }
}

.userTree-container {
  height: 250px;
  overflow-y: auto;
}

.nextPageTittle {
  text-align: left;
  line-height: 24px;
  font-size: 18px;
  color: #303133;
}

.el-button--text {
  // color: #02A7F0;
  color: #1b3f91;
  padding: 0;
  margin-bottom: 10px;
  line-height: 16px;
}

::v-deep .el-form-item__error {
  line-height: 0;
  top: 120px;
  left: -60px;
}
</style>
